<template>
  <div class="material-config-import-component">
    <el-dialog
      v-if="modelValue.visible"
      v-model="modelValue.visible"
      title="批量导入物料配置"
      width="550px"
    >
      <div style="padding-right: 20px; padding-top: 20px">
        <el-form
          :model="modelValue.form"
          :rules="modelValue.rules"
          ref="configImportRef"
          :label-width="20"
        >
          <el-form-item prop="file">
            <el-upload
              style="width: 100%"
              ref="uploadRef"
              class="upload-demo"
              :before-upload="canUpload"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :auto-upload="false"
              drag
              action="/recipeservice/materialConfig/import/excel"
              :on-change="handleFileChange"
              :file-list="modelValue.form.fileList"
              :headers="uploadHeaders"
            >
              <div class="update-demo-content">
                <div>
                  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                </div>
                <div class="el-upload__text">
                  将文件拖到此处, 或<em>点击上传</em>
                </div>
              </div>
            </el-upload>
            <div class="tip" style="font-size: 14px">
              将物料管理对应的excel拖入蓝色区域进行上传，点击<a
                style="color: #409eff"
                >下载模板</a
              >
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer v-if="!modelValue.disabled">
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="ensure"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { addUser, updateUser } from '@/api/ums-user.api'
import { ElMessage, ElUpload, ElIcon, FormInstance } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
// import { addVersion, addVersionByFile } from '@/api/sys-version-manage.api'
import { batchImportMaterialConfig } from '@/api/fms-material-config.api'

const props = defineProps(['modelValue'])

const uploadRef = ref()
const configImportRef = ref<FormInstance>()
const canUpload = async (rawFile: any) => {
  let name = rawFile.name
  let index = name.lastIndexOf('.')
  let exet = name.substring(index + 1)

  if (!(exet === 'xlsx')) {
    ElMessage({
      message: '只接受xlsx格式的excel文件',
      type: 'error',
    })
    return false
  }
  return true
}

const handleFileChange = (file: any) => {
  props.modelValue.form.fileList.push(file)
  console.log('当前文件:', file.raw) // 关键：获取原始文件对象
}

const uploadHeaders = {
  token: localStorage.getItem('TOKEN'),
}

const uploadError = (err: any, file: any, fileList: any) => {
  ElMessage({
    message: err.msg || err,
    type: 'error',
  })
}

const uploadSuccess = (response: any, file: any, fileList: any) => {
  ElMessage({
    message: '上传成功',
    type: 'success',
  })
  return
}

/***
 * 确认弹框
 */
const ensure = () => {
  let form = props.modelValue.form
  let formData = {}

  //根据 platformId 获得 platformName
  // let platFormList = props.modelValue.platFormList || []
  // let platFormItem = platFormList.find(
  //   (item: any) => item.id == form.platformId
  // )
  // if (platFormItem) {
  //   formData.platformName = platFormItem.name
  // }

  updateVersionWithFile(formData)
}

const updateVersionWithFile = (formData: any) => {
  const formData1 = new FormData()
  let fileList = props.modelValue.form.fileList || []
  // console.log('fileList:', fileList[0])
  formData1.append('file', fileList[0].raw)

  if (!configImportRef.value) return
  configImportRef.value.validate((valid, fields) => {
    if (valid) {
      batchImportMaterialConfig(formData1)
        .then((res) => {
          cancel()
          ElMessage({
            message: props.modelValue.title + '导入成功',
            type: 'success',
          })
          if (props.modelValue.refreshDataList) {
            props.modelValue.refreshDataList()
          }
        })
        .catch((err) => {
          ElMessage({
            message: err.msg || err,
            type: 'error',
          })
        })
    }
  })
}

/***
 * 取消弹框
 */
const cancel = () => {
  props.modelValue.visible = false
}
</script>

<style lang="scss" scoped>
.update-demo-content {
  display: flex;
  flex-direction: column;
}
</style>
